/*
 * DocExtUtil.java Created on 2005-3-11 10:06:01
 *
 * Copyright (c) 2001-2004 泛微软件, 版权所有.
 * Desc 此文件用于文档部分向外的接口文件
 */
package weaver.docs.docs;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.docs.category.SecCategoryComInfo;
import weaver.docs.DocDetailLog;
import weaver.file.FileUpload;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.share.ShareManager;
import weaver.workflow.request.RequestDoc;

/**
 * Description: 此文件用于文档部分向外的接口文件
 *
 * @author dongping
 * @version 1.0 2005-3-11
 */
public class DocExtUtil extends BaseBean {
	private ShareManager ShareManager = null;

	private DocComInfo dci = null;

	public DocExtUtil() {
		try {
			ShareManager = new ShareManager();
			dci = new DocComInfo();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param request
	 *            request 请求 客户端
	 * @param user
	 *            做上传的用户对象
	 * @param uploadFields
	 *            需要上传的input=file控件的名称数组
	 * @return 上传后所放文件的ID号的集合，如果id为＂-１＂表示上传此文件出现了异常，导致上传不成功
	 *         用于把一组本地文件传送到服务器，并当做附件存储在文件中 <br>
	 *         比如流程中带文件
	 */
	public int[] uploadDocsToImgs(HttpServletRequest requset, User user,
			String[] uploadFields) {
		FileUpload fu = new FileUpload(requset);
		return uploadDocsToImgs(fu, user, uploadFields);
	}

	/**
	 * @param fu
	 *            fileupload对象
	 * @param user
	 *            做上传的用户对象
	 * @param uploadFields
	 *            需要上传的input=file控件的名称数组
	 * @return 上传后所放文件的ID号的集合，如果id为＂-１＂表示上传此文件出现了异常，导致上传不成功
	 *         用于把一组本地文件传送到服务器，并当做附件存储在文件中 <br>
	 *         比如流程中带文件
	 */
	public int[] uploadDocsToImgs(FileUpload fu, User user,
			String[] uploadFields) {
		int ufsLen = uploadFields.length;
		int[] returnStrs = new int[ufsLen];
		for (int i = 0; i < ufsLen; i++) {
			if (uploadFields[i] == null)
				continue;
			returnStrs[i] = uploadDocToImg(fu, user, uploadFields[i]);
		}
		return returnStrs;
	}

    /**
	 * @param fu
	 *            fileupload对象
	 * @param user
	 *            做上传的用户对象
	 * @param uploadFields
	 *            需要上传的input=file控件的名称数组
	 * @return 上传后所放文件的ID号的集合，如果id为＂-１＂表示上传此文件出现了异常，导致上传不成功
	 *         用于把一组本地文件传送到服务器，并当做附件存储在文件中 <br>
	 *         比如流程中带文件
	 */
	public int[] uploadDocsToImgs(FileUpload fu, User user,
			String[] uploadFields,int mainid,int subid,int secid,String docsubject,String doccontent) {
		int ufsLen = uploadFields.length;
		int[] returnStrs = new int[ufsLen];
		for (int i = 0; i < ufsLen; i++) {
			if (uploadFields[i] == null)
				continue;
			returnStrs[i] = uploadDocToImg(fu, user, uploadFields[i],mainid,subid,secid,docsubject,doccontent);
		}
		return returnStrs;
	}



	/**
	 * 上传文件到服务器,不生成文档
	 * @param fu
	 * @param user
	 * @param uploadField
	 * @param docsubject
	 * @param doccontent
	 * @return
	 */
	public int uploadToImagefile(FileUpload fu, User user, String uploadField,String docsubject,String doccontent,String type) {
		String filename = "";
		int imageId=-1;
		try {
			// get doc id
			RecordSet rs = new RecordSet();
			imageId =Util.getIntValue(fu.uploadFiles(uploadField) ,-1);
			if (imageId!=-1){
				filename = fu.getFileName();
			}
			return imageId;
		} catch (Exception ex) {
			writeLog("upload file " + filename + " error!");
			writeLog(ex);
			return -1;
		}
	}

    /**
	 * @param fu
	 *            request 请求 客户端
	 * @param uploadField
	 *            需要上传的input=file控件的名称
	 * @return 只是上传一个文件并存为附件 如果 上传不成功返回值为"-1"
	 */
	public int uploadDocToImg(FileUpload fu, User user, String uploadField,int mainid,int subid,int secid,String docsubject,String doccontent) {
		String filename = "";
		try {
			// get init
			// get para
			SecCategoryComInfo scc = new SecCategoryComInfo();
			DocComInfo dc = new DocComInfo();
			DocManager dm = new DocManager();
			DocViewer dv = new DocViewer();
			DocImageManager imgManger = new DocImageManager();

			int workflowid=Util.getIntValue(fu.getParameter("workflowid"),0);

			String isWorkflowDraft="0";
			if(workflowid>0){
				RequestDoc requestDoc=new RequestDoc();
				ArrayList docFiledList=requestDoc.getDocFiled(""+workflowid);
				if(docFiledList!=null&&docFiledList.size()>6){
					isWorkflowDraft=""+docFiledList.get(6);
				}
			}
			String docStatus="1";
			if("1".equals(isWorkflowDraft)){
				docStatus="9";
			}

			// get doc id
			RecordSet rs = new RecordSet();
			int docId = dm.getNextDocId(rs);
			// upload
			// upload image file and modify table
			String imageId = fu.uploadFiles(uploadField);
			if (imageId == null)
				return -1;
			filename = fu.getFileName();
			String ext = "";
			imgManger.resetParameter();
			if ("".equals(docsubject)) {
				docsubject = getFileMainName(filename);
				imgManger.setImagefilename(filename);
				ext = getFileExt(filename);
			} else {
				imgManger.setImagefilename(docsubject);
				ext = getFileExt(docsubject);
			}

			if (ext.equalsIgnoreCase("doc")) {
				imgManger.setDocfiletype("3");
			} else if (ext.equalsIgnoreCase("xls")) {
				imgManger.setDocfiletype("4");
			} else if (ext.equalsIgnoreCase("ppt")) {
				imgManger.setDocfiletype("5");
			} else if (ext.equalsIgnoreCase("wps")) {
				imgManger.setDocfiletype("6");
			} else if (ext.equalsIgnoreCase("docx")) {
				imgManger.setDocfiletype("7");
			} else if (ext.equalsIgnoreCase("xlsx")) {
				imgManger.setDocfiletype("8");
			} else if (ext.equalsIgnoreCase("pptx")) {
				imgManger.setDocfiletype("9");
			} else if (ext.equalsIgnoreCase("et")) {
				imgManger.setDocfiletype("10");
			} else {
				imgManger.setDocfiletype("2");
			}
			imgManger.setDocid(docId);
			imgManger.setImagefileid(Util.getIntValue(imageId, 0));
			imgManger.setIsextfile("1");
			imgManger.AddDocImageInfo();

			// upload doc and modify table
			String now = "";
			String date = "";
			String time = "";
			/*now = TimeUtil.getCurrentTimeString();
			int pos = now.indexOf(" ");
			if (pos != -1) {
				date = now.substring(0, pos);
				time = now.substring(pos + 1, now.length());
			} */
            date=TimeUtil.getCurrentDateString();
            time=TimeUtil.getOnlyCurrentTimeString();

            dm.setId(docId);
			dm.setMaincategory(mainid);
			dm.setSubcategory(subid);
			dm.setSeccategory(secid);
			dm.setLanguageid(user.getLanguage());
			dm.setDoccontent(doccontent);
			dm.setDocstatus(docStatus);
			dm.setDocsubject(docsubject);
			dm.setDoccreaterid(user.getUID());
			dm.setDocCreaterType(user.getLogintype());
			dm.setUsertype(user.getLogintype());
			dm.setOwnerid(user.getUID());
			dm.setOwnerType(user.getLogintype());
			dm.setDoclastmoduserid(user.getUID());
			dm.setDocLastModUserType(user.getLogintype());
			dm.setDoccreatedate(date);
			dm.setDoclastmoddate(date);
			dm.setDoccreatetime(time);
			dm.setDoclastmodtime(time);
			dm.setDoclangurage(user.getLanguage());
			dm.setKeyword(docsubject);
			dm.setIsapprover("0");
			dm.setIsreply("");
			dm.setDocdepartmentid(user.getUserDepartment());
			dm.setDocreplyable("1");
			dm.setAccessorycount(1);
			dm.setParentids("" + docId);
			dm.setOrderable("" + scc.getSecOrderable(secid));
			dm.setClientAddress(fu.getRemoteAddr());// added by xwj for td2034
			dm.setDummycata("" + scc.getDummycata(secid));
			dm.setUserid(user.getUID()); // added by xwj for td2034 on
											// 2005-05-27
			DocCoder docCoder = new DocCoder();
			dm.setDocCode(docCoder.getDocCoder(""+secid));
			//td21527开始
			int docEdition = -1;
			int docEditionId = -1;
			 if(scc.isEditionOpen(secid)) {//如果版本管理开启
                 if(docEditionId == -1){// 如果不存在历史版本
                     docEditionId = dm.getNextEditionId(rs);
                 } else {
                     // TODO 否则，通过版本ID找到同文档的版本
                     //新建文档不存在以前有版本
                 }
                 docEdition = dc.getEdition(docEditionId)+1;
             }
			dm.setDocEditionId(docEditionId);
			dm.setDocEdition(docEdition);
			//td21527结束
			dm.AddDocInfo();
			// set share
			dm.AddShareInfo();
			dc.addDocInfoCache("" + docId);
			dv.setDocShareByDoc("" + docId);

			return docId;
		} catch (Exception ex) {
			writeLog("upload file " + filename + " error!");
			writeLog(ex);
			return -1;
		}
	}

    /**
	 * @param fu
	 *            request 请求 客户端
	 * @param uploadField
	 *            需要上传的input=file控件的名称
	 * @return 只是上传一个文件并存为附件 如果 上传不成功返回值为"-1"
	 */
	public int uploadDocToImg(FileUpload fu, User user, String uploadField) {
		String filename = "";
		try {
			// get init
			// get para
			SecCategoryComInfo scc = new SecCategoryComInfo();
			DocComInfo dc = new DocComInfo();
			DocManager dm = new DocManager();
			DocViewer dv = new DocViewer();
			DocImageManager imgManger = new DocImageManager();
			int mainId = Util.getIntValue(fu.getParameter("mainId"), -1);
			int subId = Util.getIntValue(fu.getParameter("subId"), -1);
			int secId = Util.getIntValue(fu.getParameter("secId"), -1);
			String docSubject = Util.null2String(fu.getParameter("docSubject"));
			String docContent = Util.null2String(fu.getParameter("docContent"));
			int workflowid=Util.getIntValue(fu.getParameter("workflowid"),0);

			String isWorkflowDraft="0";
			if(workflowid>0){
				RequestDoc requestDoc=new RequestDoc();
				ArrayList docFiledList=requestDoc.getDocFiled(""+workflowid);
				if(docFiledList!=null&&docFiledList.size()>6){
					isWorkflowDraft=""+docFiledList.get(6);
				}
			}
			String docStatus="1";
			if("1".equals(isWorkflowDraft)){
				docStatus="9";
			}
			// get doc id
			RecordSet rs = new RecordSet();
			int docId = dm.getNextDocId(rs);
			// upload
			// upload image file and modify table
			String imageId = fu.uploadFiles(uploadField);
			if (imageId == null)
				return -1;
			filename = fu.getFileName();
			String ext = "";
			imgManger.resetParameter();
			if ("".equals(docSubject)) {
				docSubject = getFileMainName(filename);
				imgManger.setImagefilename(filename);
				ext = getFileExt(filename);
			} else {
				imgManger.setImagefilename(docSubject);
				ext = getFileExt(docSubject);
			}

			if (ext.equalsIgnoreCase("doc")) {
				imgManger.setDocfiletype("3");
			} else if (ext.equalsIgnoreCase("xls")) {
				imgManger.setDocfiletype("4");
			} else if (ext.equalsIgnoreCase("ppt")) {
				imgManger.setDocfiletype("5");
			} else if (ext.equalsIgnoreCase("wps")) {
				imgManger.setDocfiletype("6");
			} else if (ext.equalsIgnoreCase("docx")) {
				imgManger.setDocfiletype("7");
			} else if (ext.equalsIgnoreCase("xlsx")) {
				imgManger.setDocfiletype("8");
			} else if (ext.equalsIgnoreCase("pptx")) {
				imgManger.setDocfiletype("9");
			} else if (ext.equalsIgnoreCase("et")) {
				imgManger.setDocfiletype("10");
			} else {
				imgManger.setDocfiletype("2");
			}
			imgManger.setDocid(docId);
			imgManger.setImagefileid(Util.getIntValue(imageId, 0));
			imgManger.setIsextfile("1");
			imgManger.AddDocImageInfo();

			// upload doc and modify table
			String now = "";
			String date = "";
			String time = "";
			/*now = TimeUtil.getCurrentTimeString();
			int pos = now.indexOf(" ");
			if (pos != -1) {
				date = now.substring(0, pos);
				time = now.substring(pos + 1, now.length());
			} */
            date=TimeUtil.getCurrentDateString();
            time=TimeUtil.getOnlyCurrentTimeString();

            dm.setId(docId);
			dm.setMaincategory(mainId);
			dm.setSubcategory(subId);
			dm.setSeccategory(secId);
			dm.setLanguageid(user.getLanguage());
			dm.setDoccontent(docContent);
			//dm.setDocstatus("1");
			dm.setDocstatus(docStatus);
			dm.setDocsubject(docSubject);
			dm.setDoccreaterid(user.getUID());
			dm.setDocCreaterType(user.getLogintype());
			dm.setUsertype(user.getLogintype());
			dm.setOwnerid(user.getUID());
			dm.setOwnerType(user.getLogintype());
			dm.setDoclastmoduserid(user.getUID());
			dm.setDocLastModUserType(user.getLogintype());
			dm.setDoccreatedate(date);
			dm.setDoclastmoddate(date);
			dm.setDoccreatetime(time);
			dm.setDoclastmodtime(time);
			dm.setDoclangurage(user.getLanguage());
			dm.setKeyword(docSubject);
			dm.setIsapprover("0");
			dm.setIsreply("");
			dm.setDocdepartmentid(user.getUserDepartment());
			dm.setDocreplyable("1");
			dm.setAccessorycount(1);
			dm.setParentids("" + docId);
			dm.setOrderable("" + scc.getSecOrderable(secId));
			dm.setClientAddress(fu.getRemoteAddr());// added by xwj for td2034
													// on 2005-05-27
			dm.setUserid(user.getUID()); // added by xwj for td2034 on
											// 2005-05-27
			DocCoder docCoder = new DocCoder();
			dm.setDocCode(docCoder.getDocCoder(""+secId));
			dm.setDocEditionId(dm.getNextEditionId(rs));
			dm.setDocEdition(1);

			dm.AddDocInfo();
			// set share
			dm.AddShareInfo();
			dc.addDocInfoCache("" + docId);
			dv.setDocShareByDoc("" + docId);

			return docId;
		} catch (Exception ex) {
			writeLog("upload file " + filename + " error!");
			writeLog(ex);
			return -1;
		}
	}

	/**
	 * 得到文件的扩展名
	 *
	 * @param file
	 *            文件全名
	 * @return 文件的扩展名
	 */
	public String getFileExt(String file) {
		if (file == null || file.trim().equals("")) {
			return "";
		} else {
			int idx = file.lastIndexOf(".");
			if (idx == -1) {
				return "";
			} else {
				if (idx + 1 >= file.length()) {
					return "";
				} else {
					return file.substring(idx + 1);
				}
			}
		}
	}

	private String getFileMainName(String fileName) {
		if (fileName == null)
			return "";
		//int pos = fileName.indexOf(".");
		int pos = fileName.lastIndexOf(".");
		if (pos != -1) {
			fileName = fileName.substring(0, pos);
		}
		return fileName;
	}

	/**
	 * @param docId
	 *            需要使用删除的文档ID
	 * @return ture : 删除干净 false :删除不干净
	 */
	public void deleteDoc(int docId) {
		try {
			RecordSet rs = new RecordSet();
			RecordSet rs1 = new RecordSet();
			RecordSet rs3 = new RecordSet();

			//删除回复数
	        int replydoccount = 1;
	        String pare = "";
	        String maindoc = "";
			int docid = docId;

	        String sql = "select maindoc, parentids from docdetail where id=" + docid;
	       // System.out.println(sql);
	        rs.executeSql(sql);
	        if (rs.next()) {
	            pare = rs.getString("parentids");
	            maindoc = rs.getString("maindoc");
	        }
	        //TD19610
			if(pare!=null&&!pare.equals("")){
		        //是否是最新版本的删除，老版本删除不对前级ID处理
		        if(("" + docid).equals(maindoc)) {
			        String sql2 = "update docdetail set replaydoccount=replaydoccount-" + replydoccount + " where id in (" + pare
			                + ")" + " and replaydoccount > 0";
			        rs.executeSql(sql2);
	        	}
	        }


			String delSql1 = "delete from DocDetail where id=" + docId;
			String delSql2 = "delete from DocShare where docid=" + docId;

			String delSql3 = "delete from "
					+ ShareManager.getTableName("doc", "inner")
					+ " where sourceid=" + docId; // 内部表
			String delSql4 = "delete from "
					+ ShareManager.getTableName("doc", "outer")
					+ " where sourceid=" + docId; // 外部表

			String delSql5 = "delete from DocImageFile where docid=" + docId;
			String delSql6 = "delete from docreadtag where docid=" + docId;
			String delSql7 = "delete from DocDetailLog where docid=" + docId;
			String delSql8 = "delete from docsubscribe where docid=" + docId;

			boolean isoracle = (rs.getDBType()).equals("oracle") ;
			if(isoracle){
			   rs.executeSql("delete from docdetailcontent where docid=" + docId);
			}
			/*
			String selSql1 = "select  imagefileid  from DocImageFile where docid="
					+ docId;
			rs.executeSql(selSql1);
			while (rs.next()) {
				String imagefileid = Util.null2String(rs.getString(1));
				String selSql2 = "select  filerealpath from imagefile  where imagefileid="
						+ imagefileid;
				rs1.executeSql(selSql2);
				if (rs1.next()) {
					try {
						File file = new File(Util.null2String(rs1.getString(1)));
						file.delete();
						rs3
								.executeSql("delete from imagefile where imagefileid="
										+ imagefileid);
					} catch (Exception ex) {
						continue;
					}
				}
			}
			*/
			DocImageManager imgManger = new DocImageManager();
			imgManger.setDocid(docId);
			imgManger.DeleteAllDocImageInfo();

			rs.executeSql(delSql1);
			rs.executeSql(delSql2);
			rs.executeSql(delSql3);
			rs.executeSql(delSql4);
			rs.executeSql(delSql5);
			rs.executeSql(delSql6);
			rs.executeSql(delSql7);
			rs.executeSql(delSql8);

			// TD4198 删除文档时，要清空缓存。
			dci.deleteDocInfoCache("" + docId);



		} catch (Exception ex) {
			writeLog(ex.toString());
			//System.out.println(ex);
		}
	}


	/**
     * @param docId
     * requestdeleteUtil调用
     * 传入RecordSetTrans
     *            需要使用删除的文档ID
     * @return ture : 删除干净 false :删除不干净
     */
    public void deleteDoc(RecordSetTrans rst, int docId) {
        try {
            RecordSet rs = new RecordSet();
            RecordSet rs1 = new RecordSet();
            RecordSet rs3 = new RecordSet();

            //删除回复数
            int replydoccount = 1;
            String pare = "";
            String maindoc = "";
            int docid = docId;

            String sql = "select maindoc, parentids from docdetail where id=" + docid;
           // System.out.println(sql);
            rs.executeSql(sql);
            if (rs.next()) {
                pare = rs.getString("parentids");
                maindoc = rs.getString("maindoc");
            }
            //TD19610
            if(pare!=null&&!pare.equals("")){
                //是否是最新版本的删除，老版本删除不对前级ID处理
                if(("" + docid).equals(maindoc)) {
                    String sql2 = "update docdetail set replaydoccount=replaydoccount-" + replydoccount + " where id in (" + pare
                            + ")" + " and replaydoccount > 0";
                    rs.executeSql(sql2);
                }
            }


            String delSql1 = "delete from DocDetail where id=" + docId;
            String delSql2 = "delete from DocShare where docid=" + docId;

            String delSql3 = "delete from "
                    + ShareManager.getTableName("doc", "inner")
                    + " where sourceid=" + docId; // 内部表
            String delSql4 = "delete from "
                    + ShareManager.getTableName("doc", "outer")
                    + " where sourceid=" + docId; // 外部表

            String delSql5 = "delete from DocImageFile where docid=" + docId;
            String delSql6 = "delete from docreadtag where docid=" + docId;
            String delSql7 = "delete from DocDetailLog where docid=" + docId;
            String delSql8 = "delete from docsubscribe where docid=" + docId;

            boolean isoracle = (rs.getDBType()).equals("oracle") ;
            if(isoracle){
               rs.executeSql("delete from docdetailcontent where docid=" + docId);
            }
            /*
            String selSql1 = "select  imagefileid  from DocImageFile where docid="
                    + docId;
            rs.executeSql(selSql1);
            while (rs.next()) {
                String imagefileid = Util.null2String(rs.getString(1));
                String selSql2 = "select  filerealpath from imagefile  where imagefileid="
                        + imagefileid;
                rs1.executeSql(selSql2);
                if (rs1.next()) {
                    try {
                        File file = new File(Util.null2String(rs1.getString(1)));
                        file.delete();
                        rs3
                                .executeSql("delete from imagefile where imagefileid="
                                        + imagefileid);
                    } catch (Exception ex) {
                        continue;
                    }
                }
            }
            */
            DocImageManager imgManger = new DocImageManager();
            imgManger.setDocid(docId);
            imgManger.DeleteAllDocImageInfo();

            rst.executeSql(delSql1);
            rst.executeSql(delSql2);
            rst.executeSql(delSql3);
            rst.executeSql(delSql4);
            rst.executeSql(delSql5);
            rst.executeSql(delSql6);
            rst.executeSql(delSql7);
            rst.executeSql(delSql8);

            // TD4198 删除文档时，要清空缓存。
            dci.deleteDocInfoCache("" + docId);



        } catch (Exception ex) {
            writeLog(ex.toString());
            //System.out.println(ex);
        }
    }

	/**
	 * @param docId
	 *            需要使用删除的文档ID
	 * @param user
	 *            删除文档的用户对象
	 * @param clientip
	 *            客户端ip
	 *
	 */
	public void deleteDoc(int docId ,User user,String clientip) {
		try {
			RecordSet rs = new RecordSet();
			RecordSet rs1 = new RecordSet();
			RecordSet rs3 = new RecordSet();

			//删除回复数
	        int replydoccount = 1;
	        String pare = "";
	        String maindoc = "";
			int docid = docId;

	        String sql = "select maindoc, parentids from docdetail where id=" + docid;

	        rs.executeSql(sql);
	        if (rs.next()) {
	            pare = rs.getString("parentids");
	            maindoc = rs.getString("maindoc");
	        }
	        //TD19610
			if(pare!=null&&!pare.equals("")){
		        //是否是最新版本的删除，老版本删除不对前级ID处理
		        if(("" + docid).equals(maindoc)) {
			        String sql2 = "update docdetail set replaydoccount=replaydoccount-" + replydoccount + " where id in (" + pare
			                + ")" + " and replaydoccount > 0";
			        rs.executeSql(sql2);
	        	}
	        }

	    	DocManager docManager =new DocManager();
	    	docManager.resetParameter();
	    	docManager.setId(docId);
	    	docManager.getDocInfoById();

	    	String docsubject=docManager.getDocsubject();
	        int  seccategory = docManager.getSeccategory();
	        int doccreaterid=docManager.getDoccreaterid();
	        String doccreatertype = docManager.getDocCreaterType();//文档创建者类型（1:内部用户  2：外部用户）
	        int userid=user.getUID();
	        String usertype=user.getLogintype();

			String delSql1 = "delete from DocDetail where id=" + docId;
			String delSql2 = "delete from DocShare where docid=" + docId;

			String delSql3 = "delete from "
					+ ShareManager.getTableName("doc", "inner")
					+ " where sourceid=" + docId; // 内部表
			String delSql4 = "delete from "
					+ ShareManager.getTableName("doc", "outer")
					+ " where sourceid=" + docId; // 外部表

			String delSql5 = "delete from DocImageFile where docid=" + docId;
			String delSql6 = "delete from docreadtag where docid=" + docId;
			String delSql7 = "delete from DocDetailLog where docid=" + docId;
			String delSql8 = "delete from docsubscribe where docid=" + docId;

			DocImageManager imgManger = new DocImageManager();
			imgManger.setDocid(docId);
			imgManger.DeleteAllDocImageInfo();

			rs.executeSql(delSql1);
			rs.executeSql(delSql2);
			rs.executeSql(delSql3);
			rs.executeSql(delSql4);
			rs.executeSql(delSql5);
			rs.executeSql(delSql6);
			rs.executeSql(delSql7);
			rs.executeSql(delSql8);

			// TD4198 删除文档时，要清空缓存。
			dci.deleteDocInfoCache("" + docId);

			DocDetailLog log = new DocDetailLog();
	        log.resetParameter();
	        log.setDocId(docId);
	        log.setDocSubject(docsubject);
	        log.setOperateType("3");
	        log.setOperateUserid(userid);
	        log.setUsertype(usertype);
	        log.setClientAddress(clientip);
	        log.setDocCreater(doccreaterid);
            log.setCreatertype(doccreatertype);
	        log.setDocLogInfo();

		} catch (Exception ex) {
			writeLog(ex.toString());
			//System.out.println(ex);
		}
	}

	/**
	 * 对于选择目录指定的path的附件上传的处理
	 *
	 * @param fu
	 * @param user
	 * @param uploadFields
	 * @param selectid
	 *            当为选择目录时，下拉框选择的值
	 * @param selectfieldid
	 * @return
	 */
	public int[] uploadDocsToImgsForSelect(FileUpload fu, User user,
			String[] uploadFields, int selectid, String selectfieldid) {
		int ufsLen = uploadFields.length;
		int[] returnStrs = new int[ufsLen];
		for (int i = 0; i < ufsLen; i++) {
			if (uploadFields[i] == null)
				continue;
			returnStrs[i] = uploadDocToImgForSelect(fu, user, uploadFields[i],
					selectid, selectfieldid);
		}
		return returnStrs;
	}

	/**
	 * @param Request
	 *            request 请求 客户端
	 * @param uploadField
	 *            需要上传的input=file控件的名称
	 * @return 只是上传一个文件并存为附件 如果 上传不成功返回值为"-1"
	 */
	public int uploadDocToImgForSelect(FileUpload fu, User user,
			String uploadField, int selectid, String selectfieldid) {
		String filename = "";
		String doccatelog = "";
		try {
			// get init
			// get para
			SecCategoryComInfo scc = new SecCategoryComInfo();
			DocComInfo dc = new DocComInfo();
			DocManager dm = new DocManager();
			DocViewer dv = new DocViewer();
			DocImageManager imgManger = new DocImageManager();
			int labelid = Util.getIntValue(selectfieldid, 0);
			String docSubject = Util.null2String(fu.getParameter("docSubject"));
			String docContent = Util.null2String(fu.getParameter("docContent"));
			int workflowid=Util.getIntValue(fu.getParameter("workflowid"),0);

			String isWorkflowDraft="0";
			if(workflowid>0){
				RequestDoc requestDoc=new RequestDoc();
				ArrayList docFiledList=requestDoc.getDocFiled(""+workflowid);
				if(docFiledList!=null&&docFiledList.size()>6){
					isWorkflowDraft=""+docFiledList.get(6);
				}
			}
			String docStatus="1";
			if("1".equals(isWorkflowDraft)){
				docStatus="9";
			}

			// get doc id
			RecordSet rs = new RecordSet();
			String sql = "select * from workflow_SelectItem where fieldid="
					+ labelid + " and selectvalue=" + selectid;
			rs.executeSql(sql);
			if (rs.next()) {
				doccatelog = Util.null2String(rs.getString("docCategory"));
			}
			int index = doccatelog.indexOf(",");
			int lastindex = doccatelog.lastIndexOf(",");
			int mainId = Util.getIntValue(doccatelog.substring(0, index), -1);
			int subId = Util.getIntValue(doccatelog.substring(index + 1,
					lastindex), -1);
			int secId = Util.getIntValue(doccatelog.substring(lastindex + 1),
					-1);

			int docId = dm.getNextDocId(rs);
			// upload
			// upload image file and modify table
			String imageId = fu.uploadFiles(uploadField);
			if (imageId == null)
				return -1;
			filename = fu.getFileName();
			String ext = "";
			imgManger.resetParameter();
			if ("".equals(docSubject)) {
				docSubject = getFileMainName(filename);
				imgManger.setImagefilename(filename);
				ext = getFileExt(filename);
			} else {
				imgManger.setImagefilename(docSubject);
				ext = getFileExt(docSubject);
			}

			if (ext.equalsIgnoreCase("doc")) {
				imgManger.setDocfiletype("3");
			} else if (ext.equalsIgnoreCase("xls")) {
				imgManger.setDocfiletype("4");
			} else if (ext.equalsIgnoreCase("ppt")) {
				imgManger.setDocfiletype("5");
			} else if (ext.equalsIgnoreCase("wps")) {
				imgManger.setDocfiletype("6");
			} else if (ext.equalsIgnoreCase("docx")) {
				imgManger.setDocfiletype("7");
			} else if (ext.equalsIgnoreCase("xlsx")) {
				imgManger.setDocfiletype("8");
			} else if (ext.equalsIgnoreCase("pptx")) {
				imgManger.setDocfiletype("9");
			} else if (ext.equalsIgnoreCase("et")) {
				imgManger.setDocfiletype("10");
			} else {
				imgManger.setDocfiletype("2");
			}
			imgManger.setDocid(docId);
			imgManger.setImagefileid(Util.getIntValue(imageId, 0));
			imgManger.setIsextfile("1");
			imgManger.AddDocImageInfo();

			// upload doc and modify table
			String now = "";
			String date = "";
			String time = "";
			now = TimeUtil.getCurrentTimeString();
			int pos = now.indexOf(" ");
			if (pos != -1) {
				date = now.substring(0, pos);
				time = now.substring(pos + 1, now.length());
			}

			dm.setId(docId);
			dm.setMaincategory(mainId);
			dm.setSubcategory(subId);
			dm.setSeccategory(secId);
			dm.setLanguageid(user.getLanguage());
			dm.setDoccontent(docContent);
			//dm.setDocstatus("1");
			dm.setDocstatus(docStatus);
			dm.setDocsubject(docSubject);
			dm.setDoccreaterid(user.getUID());
			dm.setDocCreaterType(user.getLogintype());
			dm.setUsertype(user.getLogintype());
			dm.setOwnerid(user.getUID());
			dm.setOwnerType(user.getLogintype());
			dm.setDoclastmoduserid(user.getUID());
			dm.setDocLastModUserType(user.getLogintype());
			dm.setDoccreatedate(date);
			dm.setDoclastmoddate(date);
			dm.setDoccreatetime(time);
			dm.setDoclastmodtime(time);
			dm.setDoclangurage(user.getLanguage());
			dm.setKeyword(docSubject);
			dm.setIsapprover("0");
			dm.setIsreply("");
			dm.setDocdepartmentid(user.getUserDepartment());
			dm.setDocreplyable("1");
			dm.setAccessorycount(1);
			dm.setParentids("" + docId);
			dm.setOrderable("" + scc.getSecOrderable(secId));
			dm.setClientAddress(fu.getRemoteAddr());// added by xwj for td2034
													// on 2005-05-27
			dm.setUserid(user.getUID()); // added by xwj for td2034 on
											// 2005-05-27
			dm.AddDocInfo();
			// set share
			dm.AddShareInfo();
			dc.addDocInfoCache("" + docId);
			dv.setDocShareByDoc("" + docId);

			return docId;
		} catch (Exception ex) {
			writeLog("upload file " + filename + " error!");
			writeLog(ex);
			return -1;
		}
	}
}
